package handler

import (
	"encoding/json"
	"oct17-test/cache"
	"oct17-test/model"
	"strconv"
	"time"

	"github.com/gin-gonic/gin"
)

// 仓库列表

func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.Query("page"))
	size, _ := strconv.Atoi(c.Query("size"))
	offset := (page - 1) * size

	var house []model.House

	redis_key := "house_list" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Offset(offset).Limit(size).Debug().Order("ID Desc").Find(&house)
		jsonData, _ := json.Marshal(house)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &house)
	}

	var total int64
	model.DB.Model(&house).Count(&total)

	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "列表获取成功",
		"data":  house,
		"total": total,
	})
	return
}
